#include <nxos.h>

NX_Error TEST_Atomic(char *cmdline)
{
    NX_Atomic a;
    NX_AtomicSet(&a, 0);
    NX_AtomicAdd(&a, 10);
    NX_AtomicAdd(&a, 5);
    NX_AtomicSub(&a, 5);
    NX_AtomicSub(&a, 5);

    /* now a = 5 */
    NX_AtomicInc(&a);
    NX_AtomicInc(&a);
    NX_AtomicDec(&a);
    NX_AtomicDec(&a);

    if (5 != NX_AtomicGet(&a))
    {
        NX_Printf("Atomic set/get, add/sub, inc/dec test failed!\n");
    }
    else
    {
        NX_Printf("Atomic set/get, add/sub, inc/dec test success!\n");
    }
    
    NX_AtomicSet(&a, 0);

    NX_AtomicSetMask(&a, 0x5A5AFF00);
    NX_AtomicClearMask(&a, 0x5A5AFF00);
    if (0 != NX_AtomicGet(&a))
    {
        NX_Printf("Atomic set/clear mask test failed!\n");
    }
    else
    {
        NX_Printf("Atomic set/clear mask test success!\n");
    }

    NX_AtomicSet(&a, 0xffff0000);
    if (NX_AtomicSwap(&a, 0x0000ffff) != 0xffff0000 && 0x0000ffff != NX_AtomicGet(&a))
    {
        NX_Printf("Atomic Swap test failed!\n");
    }
    else
    {
        NX_Printf("Atomic Swap test success!\n");
    }

    NX_AtomicSet(&a, 0x5a5af0f0);
    
    if (NX_AtomicCAS(&a, 0x5a5af0f0, 0xffff0000) != 0x5a5af0f0 && 0x5a5af0f0 != NX_AtomicGet(&a))
    {
        NX_Printf("Atomic CAS test 1 failed!\n");
    }
    else
    {
        NX_Printf("Atomic CAS test 1 success!\n");
    }

    NX_AtomicSet(&a, 0x5a5af0f0);
    
    if (NX_AtomicCAS(&a, 0xffff0000, 0x5a5af0f0) != 0x5a5af0f0  && 0x5a5af0f0 != NX_AtomicGet(&a))
    {
        NX_Printf("Atomic CAS test 2 failed!\n");
    }
    else
    {
        NX_Printf("Atomic CAS test 2 success!\n");
    }

    return NX_EOK;
}
